/**
 * huge panel container
 * Created by li-rz on 16-12-7.
 */

import './PersonalPanel.scss'
import React from 'react';

function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

class PersonalPanel extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            avatar : this.props.avatar
        }
    }

    componentDidMount(){
        var self = this
        var uploader = this.uploader = WebUploader.create({
            auto: true,
            pick: '#filePicker',
            server: `${location.protocol}//${location.hostname}:${location.port}/postFile`,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*',
            }
        })

        uploader.on( 'uploadSuccess', function( file, res) {
            var LoginToken = getCookie("LoginToken")
            fetch("/education/user/update/avatar",{
                method: 'POST',
                body:   JSON.stringify({
                    avatar : res.url,
                    LoginToken
                }),
                headers: { 'Content-Type': 'application/json' },
                credentials : "same-origin"
            })
                .then(res => res.json())
                .then(json => {
                    if(json.status == 403){
                        toastr.error("头像修改失败")
                        return
                    }

                    self.setState({
                        avatar : json.msg
                    })
                    toastr.success("头像修改成功")
                })
        })

        uploader.on( 'uploadError', function( file ) {
            toastr.error("头像上传失败，请联系管理员")
        })
    }

    render() {
        return (<div className="mooc-container mooc-panel-container">
            <div>
                <div className="mooc-panel-component">
                    <img src={this.state.avatar} className="mooc-panel"/>
                    <div className="mask_operate">
                        <div className="op_mask" />
                        <div id="filePicker" className="op_btn">
                            更改头像
                        </div>
                    </div>
                </div>
                <div className="mooc-panel-component">
                    <hgroup>
                        <h1>{this.props.username}</h1>
                        <span>{this.props.sign || "这位同学很懒，木有签名的说~"}</span>
                    </hgroup>
                </div>
            </div>
        </div>);
    }
}

PersonalPanel.PropTypes = {
    name: React.PropTypes.string,
    sign: React.PropTypes.string
};

PersonalPanel.defaultProps = {
    name: 'BMAN',
    sign: '这位同学很懒，木有签名的说~'
};


export default PersonalPanel;